package com.ship.contract.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ship.common.core.base.Page;
import com.ship.contract.bean.vo.ConShippingNameTextVo;
import com.ship.contract.bean.vo.DeliveryNoticeDetail;
import com.ship.contract.bean.vo.IhsShipBaseVo;
import com.ship.contract.service.ExportService;
import com.ship.common.core.utils.HttpRequestUtil;
import com.ship.common.core.utils.SpringUtil;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.validate.Add;
import com.ship.common.core.validate.Update;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.contract.bean.ConExcellentCases;
import com.ship.contract.bean.ConFiles;
import com.ship.contract.bean.ConResourceMemorandumPosition;
import com.ship.contract.bean.ConShipping;
import com.ship.contract.bean.vo.ConShippingRent;
import com.ship.contract.service.ConResourceMemorandumPositionService;
import com.ship.contract.service.ConShippingService;
import com.ship.contract.task.ExportContractDataTask;
import com.ship.contract.utils.ModuleConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ship.common.core.base.BaseController;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author 31463
 */
@RestController
@RequestMapping("/conShipping")
@Api(value = "conShipping", tags = "船运合同")
public class ConShippingController extends BaseController {

    @Autowired
    private ConShippingService conShippingService;

    @Autowired
    private ExportService exportService;

    @Autowired
    private HttpRequestUtil httpRequestUtil;

    @Autowired
    private SpringUtil springUtil;

    @Autowired
    private ConResourceMemorandumPositionService conResourceMemorandumPositionService;

    /**
     * 分页
     *
     * @param conShipping
     * @return
     */
    @PostMapping("/page")
    public JsonResult<Page<ConShipping>> page(@RequestBody ConShipping conShipping) {
        Page<ConShipping> page = conShippingService.page(conShipping, new QueryWrapper<ConShipping>().ne("del_apply",2).orderByDesc("delivery_date_begin"));
        if (null != page) {
            List<ConShipping> conShippings = page.getList();
            if (null != conShippings && conShippings.size() > 0) {
                conShippings.stream().forEach(c -> {
                    StringBuilder result = new StringBuilder();
                    StringBuilder deliveryNoticeDetailResult = new StringBuilder();
                    StringBuilder redeliveryNoticeDetailResult = new StringBuilder();
                    ObjectMapper objectMapper = new ObjectMapper();

                    if (StringUtils.isNotEmpty(c.getRentTimeSlot())) {
                        try {
                            List<ConShippingRent> shipRentList = objectMapper.readValue(c.getRentTimeSlot(), new TypeReference<List<ConShippingRent>>() {
                            });
                            if (null != shipRentList && shipRentList.size() > 0) {
                                shipRentList.stream().forEach(s -> {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    if (StringUtils.isNotBlank(result.toString())) {
                                        result.append(System.lineSeparator());
                                        result.append(df.format(s.getRentDateBegin()) + "至" + df.format(s.getRentDateEnd()) + ",租金：" + s.getRentParagraphStr());
                                    } else {
                                        result.append(df.format(s.getRentDateBegin()) + "至" + df.format(s.getRentDateEnd()) + ",租金：" + s.getRentParagraphStr());
                                    }
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setRentTimeSlot(result.toString());
                    }
                    if (StringUtils.isNotEmpty(c.getDeliveryNotice())) {
                        //交船通知规则
                        List<DeliveryNoticeDetail> deliveryNoticeDetailList = null;
                        try {
                            deliveryNoticeDetailList = objectMapper.readValue(c.getDeliveryNotice(), new TypeReference<List<DeliveryNoticeDetail>>() {
                            });
                            if (null != deliveryNoticeDetailList && deliveryNoticeDetailList.size() > 0) {
                                deliveryNoticeDetailResult.append("交船前 ");
                                deliveryNoticeDetailList.stream().forEach(s -> {
                                    deliveryNoticeDetailResult.append(s.getDeliveryNoticeDay()+"天 ");
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setDeliveryNotice(deliveryNoticeDetailResult.toString());
                    }
                    if (StringUtils.isNotEmpty(c.getRedeliveryNotice())) {
                        //还船通知规则
                        List<DeliveryNoticeDetail> redeliveryNoticeDetailList = null;
                        try {
                            redeliveryNoticeDetailList = objectMapper.readValue(c.getRedeliveryNotice(), new TypeReference<List<DeliveryNoticeDetail>>() {
                            });
                            if (null != redeliveryNoticeDetailList && redeliveryNoticeDetailList.size() > 0) {
                                redeliveryNoticeDetailResult.append("还船前 ");
                                redeliveryNoticeDetailList.stream().forEach(s -> {
                                    redeliveryNoticeDetailResult.append(s.getDeliveryNoticeDay()+"天 ");
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setRedeliveryNotice(redeliveryNoticeDetailResult.toString());
                    }
                    //交船状态
                    if(null !=c.getDeliveryStatusTime()){
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        c.setDeliveryStatus(c.getDeliveryStatus()+",时间："+df.format(c.getDeliveryStatusTime()));
                    }
                });
            }
        }
        return JsonResult.success(page);
    }

    /**
     * 列表查询
     *
     * @param conShipping
     * @return
     */
    @PostMapping("/list")
    public JsonResult<List<ConShipping>> list(@RequestBody ConShipping conShipping) {
        List<ConShipping> list = conShippingService.pageExportList(conShipping, new QueryWrapper<>(), new LinkedList<>());
        return JsonResult.success(list);
    }

    @GetMapping("/shipName/list")
    public JsonResult queryShipNameList(@RequestParam(required = false) String shipName){
        List<String> shipNameList = conShippingService.queryShipNameList(shipName);
        return JsonResult.success(shipNameList);
    }

    /**
     * 新增
     *
     * @param conShipping
     * @return
     */
    @PostMapping
    @Log(title = "新增船运合同", businessType = BusinessType.INSERT)
    public JsonResult add(@RequestBody @Validated(Add.class) ConShipping conShipping) {
        String conId = conShippingService.saveCon(conShipping);
        return JsonResult.success(conId);
    }

    /**
     * 修改
     *
     * @param conShipping
     * @return
     */
    @PutMapping
    @Log(title = "修改船运合同", businessType = BusinessType.UPDATE)
    public JsonResult<Object> update(@RequestBody @Validated(Update.class) ConShipping conShipping) {
        conShippingService.updateCon(conShipping);
        return JsonResult.success();
    }

    /**
     * 删除申请
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Log(title = "删除船运合同", businessType = BusinessType.DELETE)
    public JsonResult delete(@PathVariable Long id) {
        conShippingService.delApply(id);
        return JsonResult.success();
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping
    public JsonResult<Map<String, Object>> detail(Long id) {
        return JsonResult.success(conShippingService.detail(id));
    }

    /**
     * 申请优秀案例
     *
     * @param conExcellentCases
     * @return
     */
    @PostMapping("/excellent")
    public JsonResult excellent(@RequestBody ConExcellentCases conExcellentCases) {
        conShippingService.excellent(conExcellentCases, SecurityUtils.getUsername());
        return JsonResult.success();
    }

    /**
     * 导出
     *
     * @param conShipping
     * @return
     */
    @PostMapping("/export")
    @Log(title = "导出船运合同", businessType = BusinessType.EXPORT)
    public JsonResult<Object> export(@RequestBody ConShipping conShipping) {
        ExportContractDataTask task = new ExportContractDataTask();
        task.setBaseBean(conShipping);
        task.setBaseService(conShippingService);
        task.setMethodsName("export");
        task.setModule(ModuleConst.CON_SHIPPING);
        task.setDownloadFileName("导出船运合同.zip");
        task.setHttpRequestUtil(httpRequestUtil);
        task.setSpringUtil(springUtil);
        task.setUserId(SecurityUtils.getUserId());
        exportService.export(task);
        return JsonResult.success();
    }

    /**
     * 补充合同原件
     *
     * @param conFiles
     * @return
     */
    @PostMapping("/supplementaryContractFile")
    public JsonResult<Object> supplementaryContractFile(@RequestBody ConFiles conFiles) {
        conShippingService.supplementaryContractFile(conFiles);
        return JsonResult.success();
    }

    @PostMapping("/test")
    public JsonResult<ConShipping> test(@RequestBody ConShipping conShipping) {
        return JsonResult.success(conShipping);
    }

    @GetMapping("/fieldLocation")
    public JsonResult<Object> fieldLocation(String id) {
        char ch = '"';
        Long ids = Long.valueOf(id.replace(String.valueOf(ch), ""));
        List<ConResourceMemorandumPosition> result = conResourceMemorandumPositionService.getFieldLocation(ids);
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        for (ConResourceMemorandumPosition position : result) {
            String fieldName = position.getFiledName();
            Map<String, Object> fieldData = new HashMap<>();
            fieldData.put("name", position.getOldName());
            fieldData.put("x1", position.getX1());
            fieldData.put("x2", position.getX2());
            fieldData.put("y1", position.getY1());
            fieldData.put("y2", position.getY2());
            fieldData.put("page", position.getPage());
            fieldData.put("filedValue", position.getFiledValue());
            resultMap.put(fieldName + "Loc", fieldData);
        }
        return JsonResult.success(resultMap);
    }

    @ApiOperation(value = "船舶名称筛选船舶信息")
    @GetMapping(value = {"/getIhsShipBase/{name}", "/getIhsShipBase"})
    public JsonResult getIhsShipBase(@PathVariable(value = "name", required = false) String name) {
        List<IhsShipBaseVo> ihsShipBaseVos = conShippingService.getIhsShipInfo(name);
        return JsonResult.success(ihsShipBaseVos);
    }

    @ApiOperation(value = "imo筛选船舶信息")
    @GetMapping(value = {"/getIhsShipInfoByImo/{imo}", "/getIhsShipInfoByImo"})
    public JsonResult getIhsShipInfoByImo(@PathVariable(value = "imo", required = false) String imo) {
        List<IhsShipBaseVo> ihsShipBaseVos = conShippingService.getIhsShipInfoByImo(imo);
        return JsonResult.success(ihsShipBaseVos);
    }

    @GetMapping("/queryConIdByShipName")
    public JsonResult queryConIdByShipName(@RequestParam(required = false) String shipName){
        String id = conShippingService.queryConIdByShipName(shipName);
        return JsonResult.success(id);
    }

    @ApiOperation(value = "船级社/船东/租家/航运经纪人查询接口")
    @GetMapping("/selectConShippingNameTexts/{num}")
    public JsonResult selectConShippingNameTexts(@PathVariable Integer num){
        List<ConShippingNameTextVo> nameTextVos = conShippingService.selectConShippingNameTexts(num);
        return JsonResult.success(nameTextVos);
    }
}
